<?php


namespace app\index\controller;


use app\common\controller\Base;
use \think\facade\Request;
use \app\common\model\User as CommonUserModel;
use \think\facade\Session;

class User extends Base
{
    //注册页面
    public function register()
    {
        $this->isLogin();
        $token = $this->request->token('__token__', 'sha1');
        $this->assign('token', $token);

        $this->assign('title', '用户注册');
        return $this->fetch();
    }

    public function insert()
    {
        if (Request::isAjax()) {
            //验证数据
            $data = Request::post();
//            $rule = 'app\common\validate\User';//自定义的验证规则
            $rule = 'app\index\validate\User';//index/validate/User验证器
            $res = $this->validate($data, $rule);
            if (true !== $res) {
                return ['status' => -1, 'message' => $res];
            } else {
                $data = Request::except('password_confirm', 'post');
                if (CommonUserModel::create($data)) {

                    return ['status' => 1, 'message' => '注册成功'];
                } else {
                    return ['status' => 0, 'message' => '注册失败'];
                }
            }

        } else {
            dump(['status' => '-1', 'message' => '非ajax拒绝访问']);
        }
    }

    public function get_token()
    {
        $token = $this->request->token('__token__', 'sha1');
        return ['token' => "$token"];
    }

    //用户登录页面
    public function login()
    {
        $this->isLogin();
        return $this->view->fetch('login', ['title' => '用户登录']);
    }

    //用户登录验证与查询
    public function loginCheck()
    {
        if (Request::isAjax()) {
            //验证数据
            $data = Request::post();
//            $rule = 'app\common\validate\User';//自定义的验证规则
            $rule = 'app\index\validate\User.LoginCheck';//index/validate/User验证器
            $res = $this->validate($data, $rule);
            if(true !==$res){
                return ['status'=>-1,'message'=>$res];
            }
            //执行查询
            $rs = CommonUserModel::get(function ($query) use ($data) {
                $query->where('name', $data['name'])
                    ->where('password', sha1($data['password']));
            });


            if (null == $rs) {
                return ['status' => -1, 'message' => '用户名或密码不对'];
            } else {
                Session::set('user_id', $rs->id);
                Session::set('user_name', $rs->name);
                return ['status' => 1, 'message' => '登录成功'];
            }

        } else {
            $this->error("请求类型错误", 'index/user/login');
        }
    }

    //退出登录
    public function logout(){
//        Session::clear();
        Session::delete('user_id');
        Session::delete('user_name');
        $this->success('退出成功','index/index');

    }

}